package advanced.network.basic_servlet;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    private static String CRTF = System.getProperty("line.separator");
    private ServerSocket serverSocket;
    private boolean isRunning = true;

    public Server(int port) {
        start(port);
    }

    public static void main(String[] args) {
        //        使用socketServer进行网络通信, 监听8888端口
        Server server = new Server(8888);

    }

    //启动服务
    public void start(int port) {
        try {
            this.serverSocket = new ServerSocket(port);
            isRunning = true;
            receive();

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("服务启动失败");
            stop();
        }

    }

    //接收连接处理
    //使用多线程处理分发
    public void receive() {
        while (isRunning) {
            try {
                Socket client = serverSocket.accept();
                //使用多线程处理分发器
                new Thread(new Dispatcher(client)).start();

            } catch (IOException e) {
                System.out.println("客户端错误");
                isRunning = false;
            }
        }

    }


    //停止服务
    public void stop() {
        isRunning = false;
        try {
            this.serverSocket.close();
            System.out.println("服务器已停止");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
